'use client'

import { useState, useEffect, Suspense } from 'react'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { 
  ChatBubbleLeftRightIcon, 
  CheckBadgeIcon, 
  PlusIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
} from '@heroicons/react/24/outline'
import Button from '@/components/ui/Button'
import { formatDate } from '@/lib/utils'

interface User {
  id: string
  name: string
  role: string
}

interface Experiment {
  id: string
  title: string
}

interface Question {
  id: string
  title: string
  content: string
  isSolved: boolean
  viewCount: number
  createdAt: string
  author: User
  experiment: Experiment
  _count: {
    answers: number
  }
}

interface Pagination {
  total: number
  page: number
  limit: number
  pages: number
}

function ForumContent() {
  const { data: session, status } = useSession()
  const router = useRouter()
  const searchParams = useSearchParams()
  const [questions, setQuestions] = useState<Question[]>([])
  const [pagination, setPagination] = useState<Pagination>({
    total: 0,
    page: 1,
    limit: 10,
    pages: 0,
  })
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // 从URL获取查询参数
  const experimentId = searchParams.get('experimentId')
  const page = parseInt(searchParams.get('page') || '1')

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/login')
      return
    }

    if (status === 'loading') return

    fetchQuestions()
  }, [status, experimentId, page])

  const fetchQuestions = async () => {
    try {
      setLoading(true)
      let url = `/api/forum/questions?page=${page}`
      if (experimentId) {
        url += `&experimentId=${experimentId}`
      }

      const response = await fetch(url)
      
      if (!response.ok) {
        throw new Error('获取问题列表失败')
      }
      
      const data = await response.json()
      setQuestions(data.questions)
      setPagination(data.pagination)
    } catch (err: any) {
      setError(err.message || '获取问题列表失败')
    } finally {
      setLoading(false)
    }
  }

  const navigateToPage = (newPage: number) => {
    if (newPage < 1 || newPage > pagination.pages) return

    let url = `/forum?page=${newPage}`
    if (experimentId) {
      url += `&experimentId=${experimentId}`
    }
    router.push(url)
  }

  const getRoleText = (role: string) => {
    switch (role) {
      case 'ADMIN':
        return '管理员'
      case 'TEACHER':
        return '教师'
      case 'STUDENT':
        return '学生'
      default:
        return '用户'
    }
  }

  return (
    <div className="py-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center mb-6">
          <div>
            <h1 className="text-2xl font-semibold text-gray-900">实验答疑论坛</h1>
            <p className="mt-1 text-sm text-gray-600">
              {experimentId ? '当前实验的问题列表' : '所有实验的问题列表'}
            </p>
          </div>

          <Link
            href={`/forum/new${experimentId ? `?experimentId=${experimentId}` : ''}`}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700"
          >
            <PlusIcon className="-ml-1 mr-2 h-5 w-5" />
            提问
          </Link>
        </div>

        {error && (
          <div className="mb-6 rounded-md bg-red-50 p-4">
            <div className="text-sm text-red-700">{error}</div>
          </div>
        )}

        <div className="bg-white shadow overflow-hidden sm:rounded-lg">
          {loading ? (
            <div className="text-center py-12">
              <p className="text-gray-500">加载中...</p>
            </div>
          ) : questions.length === 0 ? (
            <div className="text-center py-12">
              <ChatBubbleLeftRightIcon className="mx-auto h-12 w-12 text-gray-400" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">暂无问题</h3>
              <p className="mt-1 text-sm text-gray-500">
                点击右上角的"提问"按钮开始提问
              </p>
            </div>
          ) : (
            <div className="divide-y divide-gray-200">
              {questions.map((question) => (
                <div key={question.id} className="p-6">
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <Link 
                        href={`/forum/${question.id}`}
                        className="text-lg font-medium text-primary-600 hover:text-primary-800"
                      >
                        {question.isSolved && (
                          <CheckBadgeIcon className="inline-block h-5 w-5 text-green-500 mr-1" />
                        )}
                        {question.title}
                      </Link>
                      <p className="mt-1 text-sm text-gray-500 line-clamp-2">
                        {question.content.slice(0, 150)}
                        {question.content.length > 150 ? '...' : ''}
                      </p>
                    </div>
                    <div className="ml-6 flex-shrink-0 text-center">
                      <div className="text-sm text-gray-900 font-medium">
                        {question._count.answers}
                      </div>
                      <div className="text-xs text-gray-500">回答</div>
                    </div>
                    <div className="ml-6 flex-shrink-0 text-center">
                      <div className="text-sm text-gray-900 font-medium">
                        {question.viewCount}
                      </div>
                      <div className="text-xs text-gray-500">浏览</div>
                    </div>
                  </div>
                  <div className="mt-2 flex items-center justify-between text-sm text-gray-500">
                    <div className="flex items-center">
                      <span className="mr-2">
                        {question.author.name || '匿名用户'}
                        <span className="ml-1 text-xs text-gray-400">
                          ({getRoleText(question.author.role)})
                        </span>
                      </span>
                      <span>发布于 {formatDate(new Date(question.createdAt))}</span>
                    </div>
                    <div>
                      实验: {question.experiment.title}
                    </div>
                  </div>
                </div>
              ))}

              {/* 分页 */}
              {pagination.pages > 1 && (
                <div className="px-6 py-4 flex items-center justify-between">
                  <div className="flex-1 flex justify-between sm:hidden">
                    <Button
                      onClick={() => navigateToPage(pagination.page - 1)}
                      disabled={pagination.page === 1}
                      variant="outline"
                    >
                      上一页
                    </Button>
                    <Button
                      onClick={() => navigateToPage(pagination.page + 1)}
                      disabled={pagination.page === pagination.pages}
                      variant="outline"
                    >
                      下一页
                    </Button>
                  </div>
                  <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                      <p className="text-sm text-gray-700">
                        显示第 
                        <span className="font-medium">
                          {' '}{((pagination.page - 1) * pagination.limit) + 1}{' '}
                        </span>
                        到 
                        <span className="font-medium">
                          {' '}{Math.min(pagination.page * pagination.limit, pagination.total)}{' '}
                        </span>
                        条，共 
                        <span className="font-medium">
                          {' '}{pagination.total}{' '}
                        </span>
                        条结果
                      </p>
                    </div>
                    <div>
                      <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                        <button
                          onClick={() => navigateToPage(pagination.page - 1)}
                          disabled={pagination.page === 1}
                          className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          <ChevronLeftIcon className="h-5 w-5" />
                        </button>
                        {Array.from({ length: pagination.pages }, (_, i) => i + 1).map((p) => (
                          <button
                            key={p}
                            onClick={() => navigateToPage(p)}
                            className={`relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium ${
                              p === pagination.page
                                ? 'text-primary-600 bg-primary-50'
                                : 'text-gray-700 hover:bg-gray-50'
                            }`}
                          >
                            {p}
                          </button>
                        ))}
                        <button
                          onClick={() => navigateToPage(pagination.page + 1)}
                          disabled={pagination.page === pagination.pages}
                          className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          <ChevronRightIcon className="h-5 w-5" />
                        </button>
                      </nav>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default function ForumPage() {
  return (
    <Suspense fallback={
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-12">
            <p className="text-gray-500">加载中...</p>
          </div>
        </div>
      </div>
    }>
      <ForumContent />
    </Suspense>
  )
} 